﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Remindme.Services.Interfaces;
using Remindme.ViewModel;
using Remindme.ViewModel.Interfaces;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Navigation;

namespace Remindme.Services
{
    public class NavigationService : INavigationService
    {
        private object _navigationContext;
        private Frame _rootFrame;

        public NavigationService(Frame rootFrame)
        {
            this._rootFrame = rootFrame;
        }

        public void NavigateTo(Type type)
        {
            this._rootFrame.Navigate(type);
        }

        public void NavigateTo(Type type, object navigationContext)
        {
            this._navigationContext = navigationContext;
            this._rootFrame.Navigated += OnFrameNavigated;
            this.NavigateTo(type);            
        }

        private void OnFrameNavigated(object sender, NavigationEventArgs e)
        {
            this._rootFrame.Navigated -= OnFrameNavigated;
            ((e.Content as Common.LayoutAwarePage).DataContext as INavigable).NavigationContext = this._navigationContext;
        }

        public void GoBack()
        {
            if (this._rootFrame.CanGoBack)
                this._rootFrame.GoBack();
        }

        public void GoBack(object navigationContext)
        {
            this._navigationContext = navigationContext;
            this._rootFrame.Navigated += OnFrameNavigated;
            if (this._rootFrame.CanGoBack)
                this._rootFrame.GoBack();
        }

        public void CleanHistory()
        {
            throw new NotImplementedException();
        }
    }
}
